<template>
  <view class="fix-top-window">
    <view class="uni-container dashboard-container">
    <!-- 欢迎区域 -->
    <view class="welcome-section">
      <view class="welcome-content">
        <text class="welcome-title">欢迎回来，{{ userName }}</text>
        <text class="welcome-subtitle">{{ currentTime }}</text>
      </view>
      <view class="user-role">
        <text class="role-tag">{{ userRoleName }}</text>
      </view>
    </view>

    <!-- 数据统计卡片 -->
    <view class="stats-grid">
      <view 
        v-for="(stat, index) in statsData" 
        :key="index" 
        class="stat-card"
        :style="{ borderLeftColor: stat.color }"
      >
        <view class="stat-icon" :style="{ backgroundColor: stat.color + '20' }">
          <text class="icon" :style="{ color: stat.color }">{{ stat.icon }}</text>
        </view>
        <view class="stat-content">
          <text class="stat-label">{{ stat.label }}</text>
          <text class="stat-value">{{ stat.value }}</text>
          <text class="stat-trend" :class="stat.trendType">
            {{ stat.trend }}
          </text>
        </view>
      </view>
    </view>

    <!-- 快捷操作 -->
    <view class="quick-actions-section">
      <view class="section-header">
        <text class="section-title">快捷操作</text>
      </view>
      <view class="quick-actions-grid">
        <view 
          v-for="(action, index) in quickActions" 
          :key="index"
          class="action-card"
          @click="handleQuickAction(action.path)"
        >
          <view class="action-icon" :style="{ backgroundColor: action.color + '15' }">
            <text class="icon" :style="{ color: action.color }">{{ action.icon }}</text>
          </view>
          <text class="action-label">{{ action.label }}</text>
        </view>
      </view>
    </view>

    <!-- 最近活动 -->
    <view class="recent-section">
      <view class="section-header">
        <text class="section-title">最近活动</text>
        <text class="section-more" @click="viewAllActivities">查看全部</text>
      </view>
      <view class="activity-list">
        <view 
          v-for="(activity, index) in recentActivities" 
          :key="index"
          class="activity-item"
        >
          <view class="activity-dot" :style="{ backgroundColor: activity.color }"></view>
          <view class="activity-content">
            <text class="activity-title">{{ activity.title }}</text>
            <text class="activity-time">{{ activity.time }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 待办事项 -->
    <view class="todo-section">
      <view class="section-header">
        <text class="section-title">待办事项</text>
        <text class="todo-count">{{ todoList.length }}</text>
      </view>
      <view class="todo-list">
        <view 
          v-for="(todo, index) in todoList" 
          :key="index"
          class="todo-item"
          @click="handleTodoClick(todo.path)"
        >
          <view class="todo-priority" :class="'priority-' + todo.priority"></view>
          <view class="todo-content">
            <text class="todo-title">{{ todo.title }}</text>
            <text class="todo-desc">{{ todo.description }}</text>
          </view>
          <text class="todo-arrow">›</text>
        </view>
      </view>
    </view>
    </view>
    
    <!-- #ifndef H5 -->
    <fix-window />
    <!-- #endif -->
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import config from '@/admin.config.js'
import { store as uniIdPagesStore } from '@/uni_modules/uni-id-pages/common/store.js'

// 响应式数据
const currentTime = ref('')
const statsData = ref([])
const quickActions = ref([])
const recentActivities = ref([])
const todoList = ref([])

// 计算属性
const userInfo = computed(() => uniIdPagesStore.userInfo || {})

const userName = computed(() => {
  return userInfo.value?.username || userInfo.value?.nickname || '用户'
})

const userRoleName = computed(() => {
  const roles = userInfo.value?.role || []
  if (!roles || roles.length === 0) return '访客'
  
  const roleMap = {
    'admin': '超级管理员',
    'manager': '管理员',
    'director': '院长',
    'vice_director': '副院长',
    'doctor': '医生',
    'nurse': '护士',
    'head_nurse': '护士长',
    'finance': '财务',
    'administrative': '行政',
    'purchaser': '采购员',
    'staff': '员工',
    'patient': '患者'
  }
  
  return roleMap[roles[0]] || roles[0]
})

// 生命周期
onMounted(() => {
  // 登录检查由 App.vue 和 uni-id-pages 统一处理
  // 如果用户未登录，会在 App.vue 中被拦截并跳转到登录页
  updateTime()
  loadDashboardData()
})

// 方法
const hasRole = (roles) => {
  if (!roles || roles.length === 0) return true
  const userRoles = userInfo.value?.role || []
  if (typeof roles === 'string') {
    return userRoles.includes(roles)
  }
  return roles.some(role => userRoles.includes(role))
}

const hasPermission = (permissions) => {
  if (!permissions || permissions.length === 0) return true
  const userPermissions = userInfo.value?.permission || []
  if (typeof permissions === 'string') {
    return userPermissions.includes(permissions)
  }
  return permissions.some(permission => userPermissions.includes(permission))
}

const checkLogin = () => {
  // 检查用户是否已登录
  const hasLogin = uniIdPagesStore?.hasLogin || false
  
  if (!hasLogin) {
    // 未登录，跳转到登录页
    const loginUrl = config.login?.url || '/uni_modules/uni-id-pages/pages/login/login-withpwd'
    uni.reLaunch({
      url: loginUrl
    })
    return false
  }
  
  // 检查 token 是否过期
  const tokenExpired = uni.getStorageSync('uni_id_token_expired')
  if (!tokenExpired || tokenExpired < Date.now()) {
    // token 已过期，跳转到登录页
    const loginUrl = config.login?.url || '/uni_modules/uni-id-pages/pages/login/login-withpwd'
    uni.reLaunch({
      url: loginUrl
    })
    return false
  }
  
  return true
}

const updateTime = () => {
  const now = new Date()
  const hours = now.getHours()
  let greeting = '早上好'
  if (hours >= 12 && hours < 18) {
    greeting = '下午好'
  } else if (hours >= 18) {
    greeting = '晚上好'
  }
  
  const date = now.toLocaleDateString('zh-CN', { 
    year: 'numeric', 
    month: 'long', 
    day: 'numeric',
    weekday: 'long'
  })
  
  currentTime.value = `${greeting}，今天是${date}`
}

const loadDashboardData = () => {
  // 根据角色加载不同的数据
  loadStatsData()
  loadQuickActions()
  loadRecentActivities()
  loadTodoList()
}

const loadStatsData = async () => {
  // 根据角色显示不同的统计数据
  if (hasRole(['admin', 'manager', 'director', 'vice_director'])) {
    // 查询今日预约数
    const todayStart = new Date()
    todayStart.setHours(0, 0, 0, 0)
    const todayEnd = new Date()
    todayEnd.setHours(23, 59, 59, 999)
    
    let todayAppointments = 0
    let onDutyDoctors = 0
    
    try {
      // 查询今日预约数
      const appointmentsObj = uniCloud.importObject('dh-appointments')
      const appointmentsRes = await appointmentsObj.listAppointments({
        start_date: todayStart.getTime(),
        end_date: todayEnd.getTime()
      }, 0, 1000)
      todayAppointments = appointmentsRes.data?.total || 0
      
      // 查询在岗医生数（今天有排班的医生）
      // 格式化日期为 YYYY-MM-DD 字符串格式（使用本地时间）
      const year = todayStart.getFullYear()
      const month = String(todayStart.getMonth() + 1).padStart(2, '0')
      const day = String(todayStart.getDate()).padStart(2, '0')
      const todayString = `${year}-${month}-${day}`
      
      const schedulesObj = uniCloud.importObject('dh-doctor_schedules')
      const schedulesRes = await schedulesObj.listSchedules({
        schedule_date: todayString,
        status: 1  // 只统计状态为正常的排班
      }, 0, 1000)
      
      console.log('排班查询结果:', {
        date: todayString,
        success: schedulesRes.success,
        dataType: Array.isArray(schedulesRes.data) ? 'Array' : typeof schedulesRes.data,
        dataLength: Array.isArray(schedulesRes.data) ? schedulesRes.data.length : 0,
        data: schedulesRes.data
      })
      
      // 统计不重复的医生ID数量
      const doctorIds = new Set()
      // schedulesRes.data 直接就是数组，不是 { list: [] }
      if (Array.isArray(schedulesRes.data)) {
        schedulesRes.data.forEach(schedule => {
          if (schedule.doctor_id) {
            doctorIds.add(schedule.doctor_id)
          }
        })
      }
      onDutyDoctors = doctorIds.size
      
      console.log('今日排班查询:', todayString, '结果:', Array.isArray(schedulesRes.data) ? schedulesRes.data.length : 0, '在岗医生:', onDutyDoctors)
    } catch (error) {
      console.error('加载统计数据失败:', error)
    }
    
    statsData.value = [
          {
            icon: '👥',
            label: '今日预约',
            value: todayAppointments.toString(),
            trend: '较昨日 +0%',
            trendType: 'up',
            color: '#3b82f6'
          },
          {
            icon: '👨‍⚕️',
            label: '在岗医生',
            value: onDutyDoctors.toString(),
            trend: '今日值班',
            trendType: 'up',
            color: '#10b981'
          },
          {
            icon: '💰',
            label: '今日收入',
            value: '¥0',
            trend: '较昨日 +0%',
            trendType: 'up',
            color: '#f59e0b'
          },
          {
            icon: '📦',
            label: '库存预警',
            value: '0',
            trend: '需要补货',
            trendType: 'down',
          color: '#ef4444'
      }
    ]
  } else if (hasRole(['doctor'])) {
    statsData.value = [
          {
            icon: '📅',
            label: '今日预约',
            value: '0',
            trend: '待处理',
            trendType: 'neutral',
            color: '#3b82f6'
          },
          {
            icon: '✅',
            label: '已完成',
            value: '0',
            trend: '本月',
            trendType: 'up',
            color: '#10b981'
          },
          {
            icon: '💬',
            label: '待回复咨询',
            value: '0',
            trend: '需要处理',
            trendType: 'neutral',
            color: '#f59e0b'
          },
          {
            icon: '📊',
            label: '本月收入',
            value: '¥0',
            trend: '较上月',
            trendType: 'up',
          color: '#8b5cf6'
      }
    ]
  } else if (hasRole(['nurse', 'head_nurse'])) {
    statsData.value = [
          {
            icon: '📅',
            label: '今日预约',
            value: '0',
            trend: '待协助',
            trendType: 'neutral',
            color: '#3b82f6'
          },
          {
            icon: '📦',
            label: '库存提醒',
            value: '0',
            trend: '需要关注',
            trendType: 'down',
            color: '#ef4444'
          },
          {
            icon: '👥',
            label: '患者档案',
            value: '0',
            trend: '本月新增',
            trendType: 'up',
            color: '#10b981'
          },
          {
            icon: '📋',
            label: '待办任务',
            value: '0',
            trend: '需要处理',
            trendType: 'neutral',
          color: '#f59e0b'
      }
    ]
  } else {
    statsData.value = [
          {
            icon: '📊',
            label: '本月任务',
            value: '0',
            trend: '已完成',
            trendType: 'up',
            color: '#3b82f6'
          },
          {
            icon: '📅',
            label: '今日安排',
            value: '0',
            trend: '待处理',
            trendType: 'neutral',
            color: '#10b981'
          },
          {
            icon: '⏰',
            label: '请假申请',
            value: '0',
            trend: '待审批',
            trendType: 'neutral',
            color: '#f59e0b'
          },
          {
            icon: '📝',
            label: '待办事项',
            value: '0',
            trend: '需要处理',
            trendType: 'neutral',
          color: '#8b5cf6'
      }
    ]
  }
}

const loadQuickActions = () => {
  // 根据权限显示不同的快捷操作
  const actions = []
  
  if (hasPermission('appointment:view')) {
        actions.push({
          icon: '📅',
          label: '预约管理',
          color: '#3b82f6',
          path: '/pages/business/appointments/list'
      })
  }
  
  if (hasPermission('doctor:view_all') || hasPermission('doctor:view_own')) {
        actions.push({
          icon: '👨‍⚕️',
          label: '医生管理',
          color: '#10b981',
          path: '/pages/business/doctors/list'
      })
  }
  
  if (hasPermission('patient:view_all')) {
        actions.push({
          icon: '👥',
          label: '患者管理',
          color: '#f59e0b',
          path: '/pages/business/patients/list'
      })
  }
  
  if (hasPermission('schedule:view_all') || hasPermission('schedule:view_own')) {
        actions.push({
          icon: '📆',
          label: '排班管理',
          color: '#8b5cf6',
          path: '/pages/business/doctor_schedules/list'
      })
  }
  
  if (hasPermission('inventory:view')) {
        actions.push({
          icon: '📦',
          label: '库存管理',
          color: '#ec4899',
          path: '/pages/business/inventory/list'
      })
  }
  
  if (hasPermission('income:view_all') || hasPermission('income:view_own')) {
        actions.push({
          icon: '💰',
          label: '收入管理',
          color: '#14b8a6',
          path: '/pages/business/income_records/list'
      })
  }
  
  if (hasPermission('service:manage') || hasPermission('service:browse')) {
        actions.push({
          icon: '🛠️',
          label: '服务管理',
          color: '#f97316',
          path: '/pages/business/services/list'
      })
  }
  
  if (hasPermission('consultation:view')) {
        actions.push({
          icon: '💬',
          label: '咨询管理',
          color: '#06b6d4',
          path: '/pages/business/consultations/list'
      })
  }
  
  quickActions.value = actions.slice(0, 8) // 最多显示8个
}

const loadRecentActivities = () => {
  // 模拟最近活动数据
  recentActivities.value = [
        {
          title: '系统启动成功',
          time: '刚刚',
      color: '#10b981'
    }
  ]
}

const loadTodoList = () => {
  // 根据角色加载待办事项
  const todos = []
  
  if (hasPermission('leave:approve')) {
        todos.push({
          title: '请假审批',
          description: '暂无待审批的请假申请',
          priority: 'high',
          path: '/pages/business/leave_requests/list'
      })
  }
  
  if (hasPermission('purchase_request:approve')) {
        todos.push({
          title: '采购审批',
          description: '暂无待审批的采购申请',
          priority: 'medium',
          path: '/pages/business/purchase_requests/list'
      })
  }
  
  if (hasPermission('consultation:reply')) {
        todos.push({
          title: '患者咨询',
          description: '暂无待回复的咨询',
          priority: 'medium',
          path: '/pages/business/consultations/list'
      })
  }
  
  if (hasPermission('appointment:accept')) {
        todos.push({
          title: '预约确认',
          description: '暂无待确认的预约',
          priority: 'high',
          path: '/pages/business/appointments/list'
      })
  }
  
  todoList.value = todos
}

const handleQuickAction = (path) => {
  if (path) {
    uni.navigateTo({
      url: path
    })
  }
}

const handleTodoClick = (path) => {
  if (path) {
    uni.navigateTo({
      url: path
    })
  }
}

const viewAllActivities = () => {
  uni.showToast({
    title: '功能开发中',
    icon: 'none'
  })
}
</script>

<style lang="scss" scoped>
.dashboard-container {
  background-color: #f5f7fa;
  padding: 30rpx;
}

/* 欢迎区域 */
.welcome-section {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 20rpx;
  padding: 40rpx 30rpx;
  margin-bottom: 30rpx;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 8rpx 24rpx rgba(102, 126, 234, 0.3);
}

.welcome-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 12rpx;
}

.welcome-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #ffffff;
}

.welcome-subtitle {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.85);
}

.user-role {
  .role-tag {
    background-color: rgba(255, 255, 255, 0.25);
    backdrop-filter: blur(10px);
    color: #ffffff;
    padding: 12rpx 24rpx;
    border-radius: 50rpx;
    font-size: 24rpx;
    font-weight: 500;
  }
}

/* 统计卡片网格 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 20rpx;
  margin-bottom: 30rpx;
}

.stat-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  border-left: 6rpx solid;
  display: flex;
  gap: 20rpx;
  transition: transform 0.2s;
  
  &:active {
    transform: scale(0.98);
  }
}

.stat-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .icon {
    font-size: 40rpx;
  }
}

.stat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #6b7280;
}

.stat-value {
  font-size: 36rpx;
  font-weight: bold;
  color: #1f2937;
}

.stat-trend {
  font-size: 22rpx;
  
  &.up {
    color: #10b981;
  }
  
  &.down {
    color: #ef4444;
  }
  
  &.neutral {
    color: #6b7280;
  }
}

/* 快捷操作 */
.quick-actions-section {
  margin-bottom: 30rpx;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
  padding: 0 10rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #1f2937;
}

.section-more {
  font-size: 26rpx;
  color: #667eea;
}

.quick-actions-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20rpx;
}

.action-card {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx 20rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  transition: transform 0.2s;
  
  &:active {
    transform: scale(0.95);
  }
}

.action-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  
  .icon {
    font-size: 36rpx;
  }
}

.action-label {
  font-size: 24rpx;
  color: #4b5563;
  text-align: center;
}

/* 最近活动 */
.recent-section {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.activity-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.activity-item {
  display: flex;
  gap: 20rpx;
  align-items: flex-start;
}

.activity-dot {
  width: 16rpx;
  height: 16rpx;
  border-radius: 50%;
  margin-top: 10rpx;
  flex-shrink: 0;
}

.activity-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.activity-title {
  font-size: 28rpx;
  color: #1f2937;
}

.activity-time {
  font-size: 24rpx;
  color: #9ca3af;
}

/* 待办事项 */
.todo-section {
  background-color: #ffffff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.todo-count {
  background-color: #ef4444;
  color: #ffffff;
  padding: 6rpx 16rpx;
  border-radius: 50rpx;
  font-size: 22rpx;
  font-weight: bold;
}

.todo-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.todo-item {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 24rpx;
  background-color: #f9fafb;
  border-radius: 12rpx;
  transition: background-color 0.2s;
  
  &:active {
    background-color: #f3f4f6;
  }
}

.todo-priority {
  width: 8rpx;
  height: 48rpx;
  border-radius: 4rpx;
  flex-shrink: 0;
  
  &.priority-high {
    background-color: #ef4444;
  }
  
  &.priority-medium {
    background-color: #f59e0b;
  }
  
  &.priority-low {
    background-color: #10b981;
  }
}

.todo-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.todo-title {
  font-size: 28rpx;
  color: #1f2937;
  font-weight: 500;
}

.todo-desc {
  font-size: 24rpx;
  color: #6b7280;
}

.todo-arrow {
  font-size: 48rpx;
  color: #d1d5db;
  font-weight: 300;
}
</style>

